package com.roadjava.like.security;

import java.util.concurrent.ConcurrentHashMap;

public class RateLimitService {
    private static final long TIME_FRAME_MILLIS = 60000; // 时间窗口：1分钟
    private static final int MAX_REQUESTS = 5; // 允许的最大请求次数

    // 用户的请求记录
    private final ConcurrentHashMap<String, RequestInfo> requestMap = new ConcurrentHashMap<>();

    public boolean isAllowed(String username) {
        long currentTime = System.currentTimeMillis();
        RequestInfo requestInfo = requestMap.get(username);

        if (requestInfo == null) {
            // 如果没有记录，创建新记录
            requestInfo = new RequestInfo(currentTime, 1);
            requestMap.put(username, requestInfo);
            return true;
        }

        // 如果在时间窗口内
        if (currentTime - requestInfo.timestamp < TIME_FRAME_MILLIS) {
            if (requestInfo.requestCount < MAX_REQUESTS) {
                requestInfo.requestCount++;
                return true;
            } else {
                return false; // 超过最大请求次数
            }
        } else {
            // 超出时间窗口，重置记录
            requestInfo.timestamp = currentTime;
            requestInfo.requestCount = 1;
            return true;
        }
    }

    private static class RequestInfo {
        long timestamp; // 第一次请求的时间
        int requestCount; // 请求次数

        RequestInfo(long timestamp, int requestCount) {
            this.timestamp = timestamp;
            this.requestCount = requestCount;
        }
    }
}
